package com.sell.aspect;

import com.sell.config.CookieConfig;
import com.sell.config.RedisConfig;
import com.sell.exception.SellerAuthorizeException;
import com.sell.utils.CookieUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * @author: Xukai
 * @description:
 * @createDate: 2018/7/10 11:46
 * @modified By:
 */
@Aspect
@Component
@Slf4j
public class SellerAuthorizeAspect {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private CookieConfig cookieConfig;

    @Autowired
    private RedisConfig redisConfig;

    /**
     * 定义切点，此处定义为controller层的任意类的任意方法
     */
    @Pointcut("execution(public * com.sell.controller.Seller*.*(..))" +
            "&& !execution(public * com.sell.controller.SellerUserController.*(..))")
    public void verify() {
    }

    @Before("verify()")
    public void doBefore() {
        ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = sra.getRequest();
        // 查询cookie
        Cookie cookie = CookieUtils.get(cookieConfig.getToken(), request);
        // 查询redis
        if (cookie == null) {
            log.error("【登录校验】Cookie中查不到token");
            throw new SellerAuthorizeException();
        }
        String tokenValue = redisTemplate.opsForValue().get(String.format(redisConfig.getToken_prefix(), cookie.getValue()));
        if (StringUtils.isEmpty(tokenValue)) {
            log.error("【登录校验】Redis中查不到token");
            throw new SellerAuthorizeException();
        }
    }
}
